#ifndef __TEST_UTILS_H__
#define __TEST_UTILS_H__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <sys/time.h>


#if defined __GNUC__
#define likely(x) __builtin_expect ((x), 1)
#define unlikely(x) __builtin_expect ((x), 0)
#else
#define likely(x) (x)
#define unlikely(x) (x)
#endif

static inline void err_abort(const char* errmsg)
{
#if _WIN32
    //  Raise STATUS_FATAL_APP_EXIT.
    ULONG_PTR extra_info [1];
    extra_info [0] = (ULONG_PTR) errmsg;
    RaiseException (0x40000015, EXCEPTION_NONCONTINUABLE, 1, extra_info);
#else
    (void)errmsg;
    abort ();
#endif
}

//  Provides convenient way to check for errno-style errors.
#define errno_assert(x) \
    do {\
    if (unlikely (!(x))) {\
    const char *errstr = strerror (errno);\
    fprintf (stderr, "%s (%s:%d)\n", errstr, __FILE__, __LINE__);\
    err_abort (errstr);\
    }\
    } while (0)

//  Provides convenient way to check for POSIX errors.
#define posix_assert(x) \
    do {\
    if (unlikely (!(x))) {\
    const char *errstr = strerror (x);\
    fprintf (stderr, "%s (%s:%d)\n", errstr, __FILE__, __LINE__);\
    err_abort (errstr);\
    }\
    } while (0)


static inline long long now_us()
{
#if _WIN32
    //  Get the high resolution counter's accuracy.
    LARGE_INTEGER ticksPerSecond;
    QueryPerformanceFrequency (&ticksPerSecond);

    //  What time is it?
    LARGE_INTEGER tick;
    QueryPerformanceCounter (&tick);

    //  Convert the tick number into the number of seconds
    //  since the system was started.
    double ticks_div = (double) (ticksPerSecond.QuadPart / 1000000);     
    return (long long) (tick.QuadPart / ticks_div);
#else
    struct timeval tv;
    int rc = gettimeofday(&tv, NULL);
    assert(!rc);
    return (long long)tv.tv_sec * (long long)1000000 + (long long)tv.tv_usec;
#endif
}



#endif

